package cn.edu.ncut.cs.springboot.springbootdatabase.service;

import cn.edu.ncut.cs.springboot.springbootdatabase.entity.Book;
import cn.edu.ncut.cs.springboot.springbootdatabase.repository.BookRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class BookService {

    private final BookRepository bookRepository;

    @Autowired
    public BookService(BookRepository bookRepository) {
        this.bookRepository = bookRepository;
    }

    // 获取所有书目
    public List<Book> getAllBooks() {
        return bookRepository.findAll();
    }

    // 获取书目通过ID
    public Optional<Book> getBookById(Long id) {
        return bookRepository.findById(id);
    }

    // 添加新的书目
    public Book addBook(Book book) {
        return bookRepository.save(book);
    }

    // 更新现有书目
    public Book updateBook(Long id, Book book) {
        book.setId(id);
        return bookRepository.save(book);
    }

    // 删除书目
    public void deleteBook(Long id) {
        bookRepository.deleteById(id);
    }
}
